package com.ezjie.ielts.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.widget.TextView;

import com.ezjie.ielts.R;
import com.ezjie.ielts.util.SystemTool;

/**
 * 自定义textview，实现标题显示2种颜色
 * 
 * @author renyangyang
 *
 */
public class TitleTextView extends TextView {

	private Context mContext;
	private int defaultColor = 0xffffb200;
	private int beforeColor;

	public TitleTextView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		mContext = context;
		init(attrs);
	}

	public TitleTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		init(attrs);
	}

	public TitleTextView(Context context) {
		super(context);
		mContext = context;
	}

	private void init(AttributeSet attrs) {
		TypedArray a = mContext.obtainStyledAttributes(attrs,
				R.styleable.titleTextView);
		beforeColor = a.getColor(R.styleable.titleTextView_beforeColor,
				defaultColor);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		String string = getText().toString();
		SpannableString sp = new SpannableString(string);
		if (SystemTool.PACKAGE_ZH.equals(SystemTool.getPackageName(mContext))) {
			if (string.length() >= 2) {
				int end = string.length() - 2;
				sp.setSpan(new ForegroundColorSpan(beforeColor), 0, end,
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
			setText(sp);
		} else {

			int end = string.length();
			sp.setSpan(new ForegroundColorSpan(beforeColor), 0, end,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

			setText(sp);
		}

	}

}
